package controllers

import (
	"fmt"
	//"encoding/json"
	//"fmt"
	"github.com/astaxie/beego"
	"rankEbay/rankCore"
	"strings"
)

type RankController struct {
	beego.Controller
}
func (c *RankController) RankData() {
	maxPage :=  2
	numberPerPage := 50
	itemNumbers := c.GetString("itemNumbers")
	itemNumbersSli := strings.Split(itemNumbers,",")
	keywords := c.GetString("keywords")
	keywordsSli := strings.Split(keywords, ",")
	ch := make(chan int)
	//rankCore.AllFinalRankData =rankCore.AllFinalRankData[0:0]
	//rankCore.AllFinalRankData = make([]*rankCore.FinalRank,len(keywordsSli)*len(keywordsSli))
	rankCore.AllFinalRankData = make([]*rankCore.FinalRank,0)
	fmt.Println("AllFinalRankData:",rankCore.AllFinalRankData)
	for _, itemNumber := range itemNumbersSli{
		//rankCore.AllFinalRankData[itemNumber] = make([]*rankCore.FinalRank,0)
		go c.RankOneItem(ch, itemNumber, keywordsSli, maxPage, numberPerPage)
	}
	for i:=0; i<len(itemNumbersSli)*len(keywordsSli); i++{
		//fmt.Println("oneRankRes:",oneRankRes)
		<-ch
	}
	//finalData := rankCore.AllFinalRankData
	//fmt.Println("finalData",finalData)
	//c.Data["json"] = finalData

	//data:= rankCore.AllFinalRankData
	//for i,data := range rankCore.AllFinalRankData{
	//	data1,_:=json.Marshal(&data)
    //   fmt.Println(i,":",string(data1))
	//}
	c.Data["rank"] =rankCore.AllFinalRankData
	//c.Data["json"] =rankCore.AllFinalRankData
	fmt.Println(rankCore.AllFinalRankData)
	c.TplName = "index.tpl"
	//c.ServeJSON()
}

func (c *RankController) RankOneItem(ch chan int, itemNumber string, keywordsSli []string, maxPage, numberPerPage int) {
	for i, tmp := range keywordsSli {
		keywordsSli[i] = strings.TrimSpace(tmp)
	}
	for _, v := range keywordsSli {
		go rankCore.DoSingleKeywordWork(v, maxPage, numberPerPage, itemNumber, ch)
	}
}
